<template>
  <div class="team-member-table">
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="false"
      size="small"
      bordered
      row-key="id"
    >
      <!-- 完成程度按钮插槽 -->
      <template #assignmentStatus="{ record }">
        <a-button
          type="link"
          size="small"
          @click="handleStatusChange(record)"
        >
          {{ record.assignmentStatus || '暂无状态' }}
        </a-button>
      </template>

      <!-- 操作栏插槽 -->
      <template #action="{ record }">
        <a-button
          type="link"
          size="small"
          @click="handleServiceFeedback(record)"
        >
          服务反馈
        </a-button>
      </template>
    </a-table>

    <!-- 服务反馈模态框 -->
    <a-modal
      v-model:open="feedbackModalVisible"
      title=""
      width="1200px"
      :footer="null"
      @cancel="handleCloseFeedbackModal"
      class="feedback-modal"
      :bodyStyle="{ padding: '0' }"
    >
      <div class="feedback-container">
        <div class="feedback-header">
          <div class="header-left">
            <div class="member-avatar">
              <a-avatar :size="48" style="background-color: #1890ff;">
                {{ (currentMember?.name || '未知')[0] }}
              </a-avatar>
            </div>
            <div class="member-info">
              <h3 class="member-name">{{ currentMember?.name || '未知成员' }}</h3>
              <p class="member-role">{{ currentMember?.role || '成员' }} · 服务反馈管理</p>
            </div>
          </div>
          <div class="header-actions">
            <a-button type="primary" @click="handleAddFeedback" class="add-feedback-btn">
              <template #icon>
                <Icon icon="ant-design:plus-outlined" />
              </template>
              添加服务反馈
            </a-button>
          </div>
        </div>
        
        <div class="feedback-content">

          <a-table
            :columns="feedbackColumns"
            :data-source="feedbackList"
            :loading="feedbackLoading"
            :pagination="false"
            size="middle"
            :scroll="{ x: 1000 }"
            row-key="id"
            class="feedback-table"
          >
            <!-- 操作栏插槽 -->
            <template #action="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEditFeedback(record)" class="action-btn edit-btn">
                  <template #icon>
                    <Icon icon="ant-design:edit-outlined" />
                  </template>
                  修改
                </a-button>
                <a-button type="text" size="small" @click="handleViewFeedbackFiles(record)" class="action-btn view-btn">
                  <template #icon>
                    <Icon icon="ant-design:file-text-outlined" />
                  </template>
                  文件
                </a-button>
                <a-button type="text" size="small" danger @click="handleDeleteFeedback(record)" class="action-btn delete-btn">
                  <template #icon>
                    <Icon icon="ant-design:delete-outlined" />
                  </template>
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>

    <!-- 查看反馈文件模态框 -->
    <a-modal
      v-model:open="viewFilesModalVisible"
      title="反馈文件列表"
      width="800px"
      :footer="null"
      @cancel="handleCloseFilesModal"
    >
      <div class="files-container">
        <div class="files-header">
          <h4>反馈记录: {{ currentFeedback?.question || '未知反馈' }}</h4>
          <a-button type="primary" @click="handleUploadFile" preIcon="ant-design:upload-outlined">
            上传文件
          </a-button>
        </div>

        <div class="files-list" v-if="filesList.length > 0">
          <a-list :data-source="filesList" :bordered="false">
            <template #renderItem="{ item }">
              <a-list-item>
                <div class="file-item">
                  <div class="file-info">
                    <Icon icon="ant-design:file-outlined" style="margin-right: 8px; color: #1890ff;" />
                    <span class="file-name">{{ item.fileName || item.name }}</span>
                    <span class="file-size">{{ formatFileSize(item.fileSize) }}</span>
                  </div>
                  <div class="file-actions">
                    <a-button type="link" size="small" @click="handlePreviewFile(item)">
                      预览
                    </a-button>
                    <a-button type="link" size="small" @click="handleDownloadFile(item)">
                      下载
                    </a-button>
                    <a-button type="link" size="small" danger @click="handleDeleteFile(item)">
                      删除
                    </a-button>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>

        <div v-else class="no-files">
          <a-empty description="暂无反馈文件" />
        </div>
      </div>
    </a-modal>

    <!-- 添加服务反馈模态框 -->
    <a-modal
      v-model:open="addFeedbackModalVisible"
      title=""
      width="700px"
      @ok="handleAddFeedbackConfirm"
      @cancel="handleAddFeedbackCancel"
      :confirmLoading="addFeedbackLoading"
      class="add-feedback-modal"
      :bodyStyle="{ padding: '24px 32px' }"
    >
      <div class="add-feedback-container">
        <div class="modal-header">
          <div class="header-icon">
            <Icon icon="ant-design:message-outlined" class="feedback-icon" />
          </div>
          <div class="header-content">
            <h3 class="modal-title">添加服务反馈</h3>
            <p class="modal-subtitle">为 {{ currentMember?.name || '成员' }} 创建新的服务反馈记录</p>
          </div>
        </div>
        <a-form
          ref="addFeedbackFormRef"
          :model="addFeedbackForm"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
          class="feedback-form"
        >
          <a-form-item
            label="姓名"
            name="name"
            :rules="[{ required: true, message: '请输入姓名' }]"
          >
            <a-input 
              v-model:value="addFeedbackForm.name" 
              placeholder="请输入反馈人姓名"
              size="large"
              class="form-input"
            >
              <template #prefix>
                <Icon icon="ant-design:user-outlined" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item
            label="问题"
            name="question"
            :rules="[{ required: true, message: '请输入问题描述' }]"
          >
            <a-textarea
              v-model:value="addFeedbackForm.question"
              placeholder="请详细描述遇到的问题或需要反馈的内容..."
              :rows="4"
              show-count
              :maxlength="500"
              class="form-textarea"
            />
          </a-form-item>

          <a-form-item
            label="回复"
            name="response"
            :rules="[{ required: false, message: '请输入回复内容' }]"
          >
            <a-textarea
              v-model:value="addFeedbackForm.response"
              placeholder="请输入对问题的回复或处理方案（可选）..."
              :rows="3"
              show-count
              :maxlength="300"
              class="form-textarea"
            />
          </a-form-item>

          <a-form-item
            label="状态"
            name="status"
            :rules="[{ required: false, message: '请选择处理状态' }]"
          >
            <a-select 
              v-model:value="addFeedbackForm.status" 
              placeholder="请选择处理状态"
              size="large"
              class="form-select"
            >
              <a-select-option value="待回复">
                <div class="status-option">
                  <a-tag color="orange">待回复</a-tag>
                  <span>等待处理回复</span>
                </div>
              </a-select-option>
              <a-select-option value="已回复">
                <div class="status-option">
                  <a-tag color="blue">已回复</a-tag>
                  <span>已经给出回复</span>
                </div>
              </a-select-option>
              <a-select-option value="已解决">
                <div class="status-option">
                  <a-tag color="green">已解决</a-tag>
                  <span>问题已经解决</span>
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 编辑服务反馈模态框 -->
    <a-modal
      v-model:open="editFeedbackModalVisible"
      title="编辑服务反馈"
      width="600px"
      @ok="handleEditFeedbackConfirm"
      @cancel="handleEditFeedbackCancel"
      :confirmLoading="editFeedbackLoading"
    >
      <div class="edit-feedback-container">
        <a-form
          ref="editFeedbackFormRef"
          :model="editFeedbackForm"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
          class="feedback-form"
        >
          <a-form-item
            label="姓名"
            name="name"
            :rules="[{ required: true, message: '请输入姓名' }]"
          >
            <a-input v-model:value="editFeedbackForm.name" placeholder="请输入姓名" />
          </a-form-item>

          <a-form-item
            label="问题"
            name="question"
            :rules="[{ required: true, message: '请输入问题' }]"
          >
            <a-textarea
              v-model:value="editFeedbackForm.question"
              placeholder="请输入问题描述"
              :rows="4"
            />
          </a-form-item>

          <a-form-item
            label="回复"
            name="response"
            :rules="[{ required: false, message: '请输入回复' }]"
          >
            <a-textarea
              v-model:value="editFeedbackForm.response"
              placeholder="请输入回复内容（可选）"
              :rows="4"
            />
          </a-form-item>

          <a-form-item
            label="回复状态"
            name="status"
            :rules="[{ required: false, message: '请选择回复状态' }]"
          >
            <a-select v-model:value="editFeedbackForm.status" placeholder="请选择回复状态">
              <a-select-option value="待回复">待回复</a-select-option>
              <a-select-option value="已回复">已回复</a-select-option>
              <a-select-option value="已解决">已解决</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 修改完成程度模态框 -->
    <a-modal
      v-model:open="statusModalVisible"
      title="修改完成程度"
      width="400px"
      @ok="handleStatusConfirm"
      @cancel="handleStatusCancel"
      :confirmLoading="statusLoading"
    >
      <div class="status-container">
        <a-form
          ref="statusFormRef"
          :model="statusForm"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
        >
          <a-form-item
            label="成员姓名"
            name="name"
          >
            <a-input v-model:value="statusForm.name" disabled />
          </a-form-item>

          <a-form-item
            label="完成程度"
            name="assignmentStatus"
            :rules="[{ required: true, message: '请选择完成程度' }]"
          >
            <a-select v-model:value="statusForm.assignmentStatus" placeholder="请选择完成程度">
              <a-select-option value="待开始">待开始</a-select-option>
              <a-select-option value="进行中">进行中</a-select-option>
              <a-select-option value="已完成">已完成</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 文件上传模态框 -->
    <a-modal
      v-model:open="uploadModalVisible"
      title="上传反馈文件"
      width="600px"
      @ok="handleUploadConfirm"
      @cancel="handleUploadCancel"
      :confirmLoading="uploadLoading"
    >
      <div class="upload-container">
        <a-upload
          v-model:file-list="fileList"
          :multiple="true"
          :before-upload="beforeUpload"
          @remove="handleRemove"
        >
          <a-button preIcon="ant-design:upload-outlined">
            选择文件
          </a-button>
        </a-upload>
        <div class="upload-tips">
          <p>支持多文件上传，单个文件大小不超过 50MB</p>
          <p>支持格式：图片、PDF、Word、Excel、文本文件等</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import { teamMemberColumns } from '../Tasks.data';
  import { defHttp } from '/@/utils/http/axios';
  import { message } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { useUserStore } from '/@/store/modules/user';
  import axios from 'axios';

  // 定义props
  const props = defineProps({
    taskId: {
      type: String,
      required: true,
    },
    teamId: {
      type: String,
      required: false,
    },
  });

  // 定义emit
  const emit = defineEmits(['refresh-main-table']);

  // 响应式数据
  const loading = ref(false);
  const dataSource = ref([]);
  const columns = teamMemberColumns;
  const userStore = useUserStore();

  // 服务反馈相关
  const feedbackModalVisible = ref(false);
  const feedbackLoading = ref(false);
  const feedbackList = ref([]);
  const currentMember = ref(null);

  // 查看反馈文件相关
  const viewFilesModalVisible = ref(false);
  const filesList = ref([]);
  const currentFeedback = ref(null);

  // 文件上传相关
  const uploadModalVisible = ref(false);
  const uploadLoading = ref(false);
  const fileList = ref([]);

  // 添加服务反馈相关
  const addFeedbackModalVisible = ref(false);
  const addFeedbackLoading = ref(false);
  const addFeedbackFormRef = ref();
  const addFeedbackForm = ref({
    name: '',
    question: '',
    response: '',
    status: '待回复',
  });

  // 编辑服务反馈相关
  const editFeedbackModalVisible = ref(false);
  const editFeedbackLoading = ref(false);
  const editFeedbackFormRef = ref();
  const editFeedbackForm = ref({
    id: '',
    name: '',
    question: '',
    response: '',
    status: '待回复',
  });
  const currentEditFeedback = ref(null);

  // 修改完成程度相关
  const statusModalVisible = ref(false);
  const statusLoading = ref(false);
  const statusFormRef = ref();
  const statusForm = ref({
    id: '',
    name: '',
    assignmentStatus: '',
  });
  const currentStatusRecord = ref(null);

  // 服务反馈表格列定义
  const feedbackColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '父级ID',
      dataIndex: 'parentId',
      key: 'parentId',
      width: 100,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '问题',
      dataIndex: 'question',
      key: 'question',
      width: 200,
    },
    {
      title: '回复',
      dataIndex: 'response',
      key: 'response',
      width: 200,
    },
    {
      title: '回复状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 200,
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  ];

  // 获取团队成员数据
  async function fetchTeamMembers() {
    if (!props.teamId) {
      console.warn('teamId为空，无法获取团队成员数据');
      dataSource.value = [];
      return;
    }

    loading.value = true;
    try {
      console.log('获取团队成员数据，teamId:', props.teamId);
      
      const response = await defHttp.get({
        url: '/teams/teams/queryByTaskId',
        params: { teamId: props.teamId }
      });

      console.log('团队成员数据响应:', response);

      if (response) {
        const data = response || [];
        
        if (Array.isArray(data) && data.length > 0) {
          // 处理数据
          dataSource.value = data.map((item, index) => ({
            key: item.id || index,
            id: item.id,
            name: item.name || '未知成员',
            role: item.role || '未分配',
            productName: item.productName || '暂无产品',
            assignmentContent: item.assignmentContent || item.assignment_content || item.task || '暂无任务内容',
            assignmentStatus: item.assignmentStatus || item.assignment_status || item.completion || '暂无状态',
            // 保留其他字段
            teamId: item.teamId,
            teamName: item.teamName,
            createTime: item.createTime,
          }));
          
          console.log('处理后的团队成员数据:', dataSource.value);
        } else {
          dataSource.value = [];
          console.log('团队成员数据为空');
        }
      } else {
        console.error('获取团队成员数据失败:', response);
        message.error(response?.message || '获取团队成员数据失败');
        dataSource.value = [];
      }
    } catch (error) {
      console.error('获取团队成员数据异常:', error);
      message.error('获取团队成员数据失败');
      dataSource.value = [];
    } finally {
      loading.value = false;
    }
  }

  // 服务反馈处理函数
  async function handleServiceFeedback(record: any) {
    console.log('服务反馈点击，记录:', record);
    currentMember.value = record;
    await loadFeedbackList(record.id);
    feedbackModalVisible.value = true;
  }

  // 获取服务反馈列表
  async function loadFeedbackList(teamMemberId: string) {
    if (!teamMemberId) {
      console.warn('teamMemberId为空，无法获取反馈数据');
      feedbackList.value = [];
      return;
    }

    feedbackLoading.value = true;
    try {
      console.log('获取服务反馈数据，teamMemberId:', teamMemberId);

      const response = await defHttp.get({
        url: '/sys/bussinessFeedback/queryByParentId',
        params: { id: teamMemberId },
      });

      console.log('服务反馈数据响应:', response);

      if (response) {
        const data = response || [];

        if (Array.isArray(data) && data.length > 0) {
          feedbackList.value = data.map((item: any, index: number) => ({
            key: item.id || index,
            id: item.id,
            parentId: item.parentId || item.parent_id,
            name: item.name,
            question: item.question,
            response: item.response,
            isDeleted: item.isDeleted || item.is_deleted,
            status: item.status || item.response_status,
            createTime: item.createTime || item.create_time,
          }));

          console.log('处理后的反馈数据:', feedbackList.value);
        } else {
          feedbackList.value = [];
          console.log('反馈数据为空');
        }
      } else {
        console.error('获取反馈数据失败:', response);
        message.error('获取反馈数据失败');
        feedbackList.value = [];
      }
    } catch (error) {
      console.error('获取反馈数据异常:', error);
      message.error('获取反馈数据失败');
      feedbackList.value = [];
    } finally {
      feedbackLoading.value = false;
    }
  }

  // 关闭服务反馈模态框
  function handleCloseFeedbackModal() {
    feedbackModalVisible.value = false;
    feedbackList.value = [];
    currentMember.value = null;
  }

  // 修改反馈 - 打开编辑模态框
  function handleEditFeedback(record: any) {
    console.log('编辑反馈，记录:', record);

    // 设置当前编辑的反馈记录
    currentEditFeedback.value = record;

    // 填充编辑表单
    editFeedbackForm.value = {
      id: record.id,
      name: record.name || '',
      question: record.question || '',
      response: record.response || '',
      status: record.status || '待回复',
    };

    // 打开编辑模态框
    editFeedbackModalVisible.value = true;
  }

  // 删除反馈
  async function handleDeleteFeedback(record: any) {
    try {
      console.log('删除反馈，记录:', record);

      const response = await defHttp.delete(
        {
          url: '/sys/bussinessFeedback/delete',
          params: { id: record.id },
        },
        { joinParamsToUrl: true, isTransformResponse: false }
      );

      console.log('删除反馈响应:', response);

      if (response && response.success) {
        message.success('删除反馈成功');
        // 重新加载反馈列表
        if (currentMember.value?.id) {
          await loadFeedbackList(currentMember.value.id);
        }
      } else {
        message.error(response?.message || '删除反馈失败');
      }
    } catch (error) {
      console.error('删除反馈失败:', error);
      message.error('删除反馈失败');
    }
  }

  // 查看反馈文件
  async function handleViewFeedbackFiles(record: any) {
    console.log('查看反馈文件，记录:', record);
    currentFeedback.value = record;
    await loadFeedbackFilesList(record.id);
    viewFilesModalVisible.value = true;
  }

  // 获取反馈文件列表
  async function loadFeedbackFilesList(feedbackId: string) {
    if (!feedbackId) {
      console.warn('feedbackId为空，无法获取文件数据');
      filesList.value = [];
      return;
    }

    try {
      console.log('获取反馈文件数据，feedbackId:', feedbackId);

      const response = await defHttp.get({
        url: '/sys/bussinessFeedback/getFiles',
        params: { id: feedbackId },
      });

      console.log('反馈文件数据响应:', response);

      if (response) {
        const data = response || [];

        if (Array.isArray(data) && data.length > 0) {
          filesList.value = data;
          console.log('处理后的文件数据:', filesList.value);
        } else {
          filesList.value = [];
          console.log('文件数据为空');
        }
      } else {
        console.error('获取文件数据失败:', response);
        message.error('获取文件数据失败');
        filesList.value = [];
      }
    } catch (error) {
      console.error('获取文件数据异常:', error);
      message.error('获取文件数据失败');
      filesList.value = [];
    }
  }

  // 关闭反馈文件模态框
  function handleCloseFilesModal() {
    viewFilesModalVisible.value = false;
    filesList.value = [];
    currentFeedback.value = null;
  }

  // 预览文件（参考合同表的实现）
  async function handlePreviewFile(file: any) {
    try {
      if (!file.id) {
        message.warning('未找到文件ID');
        return;
      }

      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/sys/bussinessFeedback/previewFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      window.open(url, '_blank');
      console.log('文件预览请求已发送:', url);
    } catch (error) {
      console.error('预览文件失败:', error);
      message.error('预览文件失败');
    }
  }

  // 下载文件（参考合同表的实现）
  async function handleDownloadFile(file: any) {
    try {
      if (!file.id) {
        message.warning('未找到文件ID');
        return;
      }

      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/sys/bussinessFeedback/downloadFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      const a = document.createElement('a');
      a.href = url;
      a.download = file.fileName || file.name || '反馈文件';
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      console.log('文件下载请求已发送:', url);
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败');
    }
  }

  // 删除文件（参考合同表的实现）
  async function handleDeleteFile(file: any) {
    try {
      if (!file.id) {
        message.warning('未找到文件ID');
        return;
      }

      console.log('删除文件，文件ID:', file.id);

      const response = await defHttp.delete(
        {
          url: '/sys/bussinessFeedback/deleteFile',
          params: { fileId: file.id },
        },
        { joinParamsToUrl: true, isTransformResponse: false }
      );

      console.log('删除文件响应:', response);

      if (response && response.success) {
        message.success('删除文件成功');
        // 重新加载文件列表
        if (currentFeedback.value?.id) {
          await loadFeedbackFilesList(currentFeedback.value.id);
        }
      } else {
        message.error(response?.message || '删除文件失败');
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      message.error('删除文件失败');
    }
  }

  // 格式化文件大小（参考合同表的实现）
  function formatFileSize(size: number): string {
    if (!size) return '';
    if (size < 1024) return size + ' B';
    if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB';
    if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB';
    return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
  }

  // 文件上传相关函数
  function handleUploadFile() {
    if (!currentFeedback.value?.id) {
      message.warning('请先选择反馈记录');
      return;
    }
    fileList.value = [];
    uploadModalVisible.value = true;
  }

  function beforeUpload(file: any) {
    console.log('文件上传前验证:', {
      name: file.name,
      size: file.size,
      type: file.type,
      sizeMB: (file.size / 1024 / 1024).toFixed(2) + 'MB'
    });

    // 检查文件大小（降低到50MB限制，避免超时）
    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isLt50M) {
      message.error('文件大小不能超过 50MB!');
      return false;
    }

    // 检查文件类型（可选，根据需要添加）
    const allowedTypes = [
      'image/jpeg', 'image/png', 'image/gif', 'image/bmp',
      'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'text/plain', 'application/zip', 'application/rar'
    ];

    // 如果需要限制文件类型，取消下面的注释
    // if (!allowedTypes.includes(file.type)) {
    //   message.error('不支持的文件类型!');
    //   return false;
    // }

    return false; // 阻止自动上传
  }

  function handleRemove(file: any) {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  }

  async function handleUploadConfirm() {
    if (fileList.value.length === 0) {
      message.warning('请选择要上传的文件');
      return;
    }

    if (!currentFeedback.value?.id) {
      message.warning('反馈记录ID不存在');
      return;
    }

    uploadLoading.value = true;
    try {
      // 逐个上传文件
      for (const file of fileList.value) {
        // 检查文件对象
        const fileObj = file.originFileObj || file;
        if (!fileObj) {
          throw new Error(`文件 ${file.name} 对象无效`);
        }

        console.log('准备上传文件:', {
          name: file.name,
          size: fileObj.size,
          type: fileObj.type,
          feedbackId: currentFeedback.value.id
        });

        const formData = new FormData();
        formData.append('id', currentFeedback.value.id);
        formData.append('file', fileObj);

        console.log('FormData内容:', {
          id: currentFeedback.value.id,
          fileName: file.name,
          fileSize: fileObj.size
        });

        // 使用axios直接发送请求，参考合同文件上传的方式
        const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
        const response = await axios.post(`${baseUrl}/sys/bussinessFeedback/uploadFile`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'X-Access-Token': userStore.getToken,
          },
          timeout: 60000, // 设置60秒超时
          onUploadProgress: (progressEvent: any) => {
            if (progressEvent.total) {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              console.log(`上传进度: ${percentCompleted}%`);
            }
          },
        });

        console.log('上传响应:', response.data);

        if (!response.data || !response.data.success) {
          throw new Error(response.data?.message || `上传文件 ${file.name} 失败`);
        }
      }

      message.success(`成功上传 ${fileList.value.length} 个文件`);
      uploadModalVisible.value = false;
      fileList.value = [];

      // 重新加载文件列表
      if (currentFeedback.value?.id) {
        await loadFeedbackFilesList(currentFeedback.value.id);
      }
    } catch (error) {
      console.error('上传文件失败:', error);
      if (error.message && error.message.includes('timeout')) {
        message.error('文件上传超时，请检查网络连接或尝试上传较小的文件');
      } else if (error.response) {
        // axios错误响应
        const errorMsg = error.response.data?.message || error.response.statusText || '上传文件失败';
        message.error(`上传失败: ${errorMsg}`);
      } else {
        message.error(error.message || '上传文件失败');
      }
    } finally {
      uploadLoading.value = false;
    }
  }

  function handleUploadCancel() {
    uploadModalVisible.value = false;
    fileList.value = [];
  }

  // 添加服务反馈相关函数
  function handleAddFeedback() {
    if (!currentMember.value?.id) {
      message.warning('请先选择团队成员');
      return;
    }

    // 重置表单，自动填充成员姓名
    addFeedbackForm.value = {
      name: currentMember.value.name || '',
      question: '',
      response: '',
      status: '待回复',
    };

    addFeedbackModalVisible.value = true;
  }

  async function handleAddFeedbackConfirm() {
    try {
      // 验证表单
      await addFeedbackFormRef.value?.validate();

      if (!currentMember.value?.id) {
        message.warning('团队成员ID不存在');
        return;
      }

      addFeedbackLoading.value = true;

      // 准备提交数据
      const submitData = {
        ...addFeedbackForm.value,
        parentId: currentMember.value.id, // 自动传入当前成员ID作为父级ID
        teamMemberId: currentMember.value.id, // 关联团队成员ID
        isDeleted: 0,
      };

      console.log('添加服务反馈，提交数据:', submitData);

      const response = await defHttp.post({
        url: '/sys/bussinessFeedback/add',
        data: submitData,
      });

      if (response) {
        message.success('添加服务反馈成功');
        addFeedbackModalVisible.value = false;

        // 重新加载反馈列表
        if (currentMember.value?.id) {
          await loadFeedbackList(currentMember.value.id);
        }
      } else {
          message.error('添加服务反馈失败');
      }
    } catch (error) {
      console.error('添加服务反馈失败:', error);
      if (error.errorFields) {
        message.error('请检查表单输入');
      } else {
        message.error('添加服务反馈失败');
      }
    } finally {
      addFeedbackLoading.value = false;
    }
  }

  function handleAddFeedbackCancel() {
    addFeedbackModalVisible.value = false;
    // 重置表单
    addFeedbackForm.value = {
      name: '',
      question: '',
      response: '',
      status: '待回复',
    };
  }

  // 编辑服务反馈确认
  async function handleEditFeedbackConfirm() {
    try {
      // 验证表单
      await editFeedbackFormRef.value?.validate();

      if (!editFeedbackForm.value.id) {
        message.warning('反馈记录ID不存在');
        return;
      }

      editFeedbackLoading.value = true;

      // 准备提交数据
      const submitData = {
        ...editFeedbackForm.value,
      };

      console.log('编辑服务反馈，提交数据:', submitData);

      const response = await defHttp.post({
        url: '/sys/bussinessFeedback/edit',
        data: submitData,
      });

      if (response) {
        message.success('编辑服务反馈成功');
        editFeedbackModalVisible.value = false;

        // 重新加载反馈列表
        if (currentMember.value?.id) {
          await loadFeedbackList(currentMember.value.id);
        }
      } else {
        message.error('编辑服务反馈失败');
      }
    } catch (error) {
      console.error('编辑服务反馈失败:', error);
      if (error.errorFields) {
        message.error('请检查表单输入');
      } else {
        message.error('编辑服务反馈失败');
      }
    } finally {
      editFeedbackLoading.value = false;
    }
  }

  // 编辑服务反馈取消
  function handleEditFeedbackCancel() {
    editFeedbackModalVisible.value = false;
    currentEditFeedback.value = null;
    // 重置表单
    editFeedbackForm.value = {
      id: '',
      name: '',
      question: '',
      response: '',
      status: '待回复',
    };
  }

  // 修改完成程度 - 打开状态修改模态框
  function handleStatusChange(record: any) {
    console.log('修改完成程度，记录:', record);

    // 设置当前修改的记录
    currentStatusRecord.value = record;

    // 填充状态表单
    statusForm.value = {
      id: record.id,
      name: record.name || '',
      assignmentStatus: record.assignmentStatus || '待开始',
    };

    // 打开状态修改模态框
    statusModalVisible.value = true;
  }

  // 状态修改确认
  async function handleStatusConfirm() {
    try {
      // 验证表单
      await statusFormRef.value?.validate();

      if (!statusForm.value.id) {
        message.warning('记录ID不存在');
        return;
      }

      statusLoading.value = true;

      // 获取当前修改的行数据
      const currentRowData = {
        ...currentStatusRecord.value,
        // 更新完成程度字段
        assignmentStatus: statusForm.value.assignmentStatus
      };

      console.log('更新任务状态，提交数据:', currentRowData);

      // 1. 先更新子表数据
      const response = await defHttp.post({
        url: '/teams/teams/updateTaskStatus',
        data: currentRowData,
      });

      if (response) {
        message.success('修改完成程度成功');

        // 2. 检查是否需要更新主表状态
        await checkAndUpdateMainTableStatus();

        statusModalVisible.value = false;

        // 重新加载团队成员数据
        await fetchTeamMembers();
      } else {
        message.error(response?.message || '修改完成程度失败');
      }
    } catch (error) {
      console.error('修改完成程度失败:', error);
      if (error.errorFields) {
        message.error('请检查表单输入');
      } else {
        message.error('修改完成程度失败');
      }
    } finally {
      statusLoading.value = false;
    }
  }

  // 检查并更新主表状态
  async function checkAndUpdateMainTableStatus() {
    try {
      const currentAssignmentStatus = statusForm.value.assignmentStatus;

      if (currentAssignmentStatus === '已完成') {
        // 如果当前修改行状态为已完成，检查所有行是否都已完成
        console.log('当前修改状态为已完成，检查所有子表数据...');

        // 获取更新后的所有子表数据（模拟更新后的状态）
        const updatedDataSource = dataSource.value.map((item: any) => {
          if (item.id === statusForm.value.id) {
            return { ...item, assignmentStatus: currentAssignmentStatus };
          }
          return item;
        });

        // 检查是否所有行都已完成
        const allCompleted = updatedDataSource.every((item: any) => item.assignmentStatus === '已完成');

        if (allCompleted) {
          console.log('所有子表行都已完成，更新主表状态为已完成');
          await updateMainTableStatus('已完成');
        }
      } else {
        // 如果当前修改行状态不是已完成，更新主表状态为进行中
        console.log('当前修改状态不是已完成，更新主表状态为进行中');
        await updateMainTableStatus('进行中');
      }
    } catch (error) {
      console.error('检查并更新主表状态失败:', error);
      // 这里不抛出错误，避免影响子表更新的成功提示
    }
  }

  // 更新主表状态
  async function updateMainTableStatus(newStatus: string) {
    try {
      console.log('开始更新主表状态为:', newStatus);
      console.log('当前teamId:', props.teamId);

      if (!props.teamId) {
        console.error('teamId为空，无法更新主表状态');
        message.warning('团队ID为空，无法更新任务状态');
        return;
      }

      const updateData = {
        teamId: props.teamId,
        status: newStatus,
      };

      console.log('更新主表状态，提交数据:', updateData);
      console.log('请求URL:', '/teams/teams/updateTaskStatusByTeamId');

      // 尝试使用axios直接发送请求，避免defHttp的拦截器问题
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const response = await axios.post(`${baseUrl}/teams/teams/updateTaskStatusByTeamId`, updateData, {
        headers: {
          'Content-Type': 'application/json',
          'X-Access-Token': userStore.getToken,
        },
        timeout: 30000, // 30秒超时
      });

      console.log('更新主表状态响应:', response);
      console.log('响应数据:', response.data);

      if (response.data) {
        console.log(`主表状态已更新为: ${newStatus}`);
        message.success(`任务状态已更新为: ${newStatus}`);

        // 刷新主表数据
        await refreshMainTableData();
      } else {
        console.error('更新主表状态失败1 - 响应数据为空');
        message.warning('更新任务状态失败 - 服务器响应为空');
      }
    } catch (error) {
      console.error('更新主表状态失败2:', error);
      console.error('错误详情:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        config: error.config
      });

      // 尝试备用请求方式
      await tryAlternativeRequest(newStatus);
    }
  }

  // 备用请求方式
  async function tryAlternativeRequest(newStatus: string) {
    try {
      console.log('尝试备用请求方式 - 使用表单数据格式');

      const formData = new FormData();
      formData.append('teamId', props.teamId);
      formData.append('status', newStatus);

      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const response = await axios.post(`${baseUrl}/teams/teams/updateTaskStatusByTeamId`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'X-Access-Token': userStore.getToken,
        },
        timeout: 30000,
      });

      console.log('备用方式响应:', response.data);

      if (response.data) {
        console.log(`主表状态已更新为: ${newStatus}`);
        message.success(`任务状态已更新为: ${newStatus}`);

        // 刷新主表数据
        await refreshMainTableData();
      } else {
        console.error('备用方式也失败');
        message.warning('更新任务状态失败');
      }
    } catch (error) {
      console.error('备用方式也失败:', error);

      // 最后尝试使用defHttp但添加更多配置
      try {
        console.log('最后尝试使用defHttp with 特殊配置');
        const response = await defHttp.post(
          {
            url: '/teams/teams/updateTaskStatusByTeamId',
            data: {
              teamId: props.teamId,
              status: newStatus,
            },
          },
          {
            joinParamsToUrl: false,
            isTransformResponse: false,
            errorMessageMode: 'none'
          }
        );

        console.log('defHttp特殊配置响应:', response);

        if (response) {
          message.success(`任务状态已更新为: ${newStatus}`);

          // 刷新主表数据
          await refreshMainTableData();
        } else {
          message.error('更新任务状态失败，请检查网络连接或联系管理员');
        }
      } catch (finalError) {
        console.error('所有方式都失败:', finalError);
        message.error('更新任务状态失败，请检查网络连接或联系管理员');
      }
    }
  }
  // 状态修改取消
  function handleStatusCancel() {
    statusModalVisible.value = false;
    currentStatusRecord.value = null;
    // 重置表单
    statusForm.value = {
      id: '',
      name: '',
      assignmentStatus: '',
    };
  }

  // 刷新主表数据
  async function refreshMainTableData() {
    try {
      console.log('开始刷新主表数据...');

      // 通知父组件重新加载表格数据
      emit('refresh-main-table');

      console.log('已通知父组件重新加载任务表数据');
    } catch (error) {
      console.error('刷新主表数据失败:', error);
    }
  }

  // 监听teamId变化
  watch(() => props.teamId, (newTeamId) => {
    if (newTeamId) {
      fetchTeamMembers();
    } else {
      dataSource.value = [];
    }
  }, { immediate: true });

  // 组件挂载时获取数据
  onMounted(() => {
    if (props.teamId) {
      fetchTeamMembers();
    }
  });

  // 暴露刷新方法
  defineExpose({
    refresh: fetchTeamMembers,
  });
</script>

<style lang="less" scoped>
  .team-member-table {
    margin: 16px 0;

    :deep(.ant-table) {
      .ant-table-tbody > tr > td {
        padding: 8px 12px;
      }
    }
  }

  .feedback-container {
    .feedback-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      margin: -24px -24px 24px -24px;
      padding: 24px 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-radius: 8px 8px 0 0;

      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;

        .member-avatar {
          .ant-avatar {
            border: 3px solid rgba(255, 255, 255, 0.3);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }

        .member-info {
          .member-name {
            margin: 0;
            color: white;
            font-size: 18px;
            font-weight: 600;
          }

          .member-role {
            margin: 4px 0 0 0;
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
          }
        }
      }

      .header-actions {
        .add-feedback-btn {
          background: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: white;
          font-weight: 500;
          height: 40px;
          padding: 0 20px;
          border-radius: 20px;
          backdrop-filter: blur(10px);
          transition: all 0.3s;

          &:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
          }

          .anticon {
            font-size: 16px;
          }
        }
      }
    }

    .feedback-content {
      .feedback-table {
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

        :deep(.ant-table-thead > tr > th) {
          background: #fafafa;
          border-bottom: 2px solid #e8e8e8;
          font-weight: 600;
          color: #333;
          padding: 16px 12px;
        }

        :deep(.ant-table-tbody > tr > td) {
          padding: 12px;
          border-bottom: 1px solid #f0f0f0;
        }

        :deep(.ant-table-tbody > tr:hover > td) {
          background: #f8f9ff;
        }

        .action-btn {
          border-radius: 6px;
          transition: all 0.3s;
          
          &.edit-btn {
            color: #1890ff;
            &:hover {
              background: #e6f7ff;
              border-color: #1890ff;
            }
          }

          &.view-btn {
            color: #52c41a;
            &:hover {
              background: #f6ffed;
              border-color: #52c41a;
            }
          }

          &.delete-btn {
            color: #ff4d4f;
            &:hover {
              background: #fff2f0;
              border-color: #ff4d4f;
            }
          }
        }
      }
    }
  }

  .add-feedback-container {
    .modal-header {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 32px;
      padding-bottom: 20px;
      border-bottom: 2px solid #f0f0f0;

      .header-icon {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        background: linear-gradient(135deg, #1890ff, #36cfc9);
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);

        .feedback-icon {
          font-size: 24px;
          color: white;
        }
      }

      .header-content {
        .modal-title {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          color: #262626;
        }

        .modal-subtitle {
          margin: 4px 0 0 0;
          color: #8c8c8c;
          font-size: 14px;
        }
      }
    }
    
    .feedback-form {
      .ant-form-item {
        margin-bottom: 24px;
        
        .ant-form-item-label {
          text-align: left;
          padding-right: 12px;
          
          > label {
            font-weight: 600;
            color: #262626;
            font-size: 15px;
          }
        }
        
        .ant-form-item-control {
          .form-input {
            border-radius: 8px;
            border: 2px solid #e8e8e8;
            transition: all 0.3s;
            font-size: 14px;
            
            &:hover {
              border-color: #40a9ff;
            }
            
            &:focus, &.ant-input-focused {
              border-color: #1890ff;
              box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
            }

            .anticon {
              color: #8c8c8c;
            }
          }

          .form-textarea {
            border-radius: 8px;
            border: 2px solid #e8e8e8;
            transition: all 0.3s;
            font-size: 14px;
            resize: vertical;
            
            &:hover {
              border-color: #40a9ff;
            }
            
            &:focus, &.ant-input-focused {
              border-color: #1890ff;
              box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
            }
          }

          .form-select {
            border-radius: 8px;
            
            :deep(.ant-select-selector) {
              border: 2px solid #e8e8e8;
              border-radius: 8px;
              transition: all 0.3s;
            }

            &:hover :deep(.ant-select-selector) {
              border-color: #40a9ff;
            }

            &.ant-select-focused :deep(.ant-select-selector) {
              border-color: #1890ff;
              box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
            }
          }

          .status-option {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 4px 0;

            span {
              font-size: 13px;
              color: #666;
            }
          }
        }
      }
    }
  }

  .edit-feedback-container {
    padding: 8px 0;
    
    .feedback-form {
      margin-top: 8px;
      
      .ant-form-item {
        margin-bottom: 20px;
        
        .ant-form-item-label {
          text-align: left;
          padding-right: 12px;
          
          > label {
            font-weight: 500;
            color: #333;
            font-size: 14px;
          }
        }
        
        .ant-form-item-control {
          .ant-input, .ant-select, .ant-input-number {
            border-radius: 6px;
            border: 1px solid #d9d9d9;
            transition: all 0.3s;
            
            &:hover {
              border-color: #40a9ff;
            }
            
            &:focus, &.ant-input-focused, &.ant-select-focused {
              border-color: #1890ff;
              box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
            }
          }
          
          .ant-input {
            padding: 8px 12px;
          }
          
          textarea.ant-input {
            padding: 8px 12px;
            resize: vertical;
            min-height: 80px;
          }
        }
      }
    }
  }

  .status-container {
    .ant-form {
      margin-top: 16px;
    }
  }

  .files-container {
    .files-header {
      margin-bottom: 16px;

      h4 {
        margin: 0;
        color: #333;
      }
    }

    .files-list {
      .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;

        .file-info {
          display: flex;
          align-items: center;
          flex: 1;

          .file-name {
            margin-right: 16px;
            font-weight: 500;
          }

          .file-size {
            color: #999;
            font-size: 12px;
          }
        }

        .file-actions {
          display: flex;
          gap: 8px;
        }
      }
    }

    .no-files {
      text-align: center;
      padding: 40px 0;
    }
  }

  .upload-container {
    .upload-tips {
      margin-top: 16px;

      p {
        margin: 0;
        color: #666;
        font-size: 12px;
      }
    }
  }
</style>
